//
//  HPSignTransactionViewController.m
//  HPZZTong
//
//  Created by handpay on 14-4-25.
//  Copyright (c) 2014年 Handpay. All rights reserved.
//

#import "HPSignTransactionViewController.h"
#import "ZZTongUtility.h"
#import "CategoryUtil.h"
#import <HandPaySwiperModule/HandPaySwiperModule.h>

@interface HPSignTransactionViewController ()
{
    
    IBOutlet UIView *bgView;
    IBOutlet UIButton *comButton;
    IBOutlet UIScrollView *bgScrollView;
    IBOutlet UIView *aboveView;
    IBOutlet UIView *signView;
    
    IBOutlet UILabel *remarksLabel;
    IBOutlet UILabel *tipsLabel;
    IBOutlet UILabel *amountLabel;
    IBOutlet UILabel *cardORGLabel;
    IBOutlet UILabel *refNoLabel;
    IBOutlet UILabel *dateTimeLabel;
    IBOutlet UILabel *authNoLabel;
    IBOutlet UILabel *vaucherNoLabel;
    IBOutlet UILabel *batchNoLabel;
    IBOutlet UILabel *expDateLabel;
    IBOutlet UILabel *txnTypeLabel;
    IBOutlet UILabel *acqNoLabel;
    IBOutlet UILabel *issNOLabel;
    IBOutlet UILabel *cardNumberLabel;
    IBOutlet UILabel *operatiorNoLabel;
    IBOutlet UILabel *terminalNoLabel;
    IBOutlet UILabel *merchantNoLabel;
    IBOutlet UILabel *merchantLabel;
    
}

@property(nonatomic, retain)UIButton* signButton;
@property(nonatomic, retain)NSString* mobilePhone;
@property(nonatomic, retain)UIImage* signImage;

- (IBAction)comButtonClick:(id)sender;

@end

@implementation HPSignTransactionViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
    }
    return self;
}
- (void)addSuccessImage{
    int w = 157;
    int top = ((bgView.frame.size.height - 50) - w ) / 2;
    UIImageView* failImageV = [[UIImageView alloc]initWithFrame:CGRectMake(100, top, 157, 157)];
    failImageV.image = [UIImage imageNamed:@"successstamp.png"];
    [bgView addSubview:failImageV];
    [failImageV release];
}
- (void)viewDidLoad
{
    self.title = @"交易详情";
    [super viewDidLoad];
    
    NSString* bussinesType = [screenData objectForKey:kBusinissType];
    
    //    if (bussinesType && [bussinesType isEqualToString:transRecord] ) {
    //        comButton.hidden = YES;
    //    }
    
    UIImage* signImage = [self.screenData objectForKey:kSignImage];
    if (bussinesType && [bussinesType isEqualToString:transRecord]) {
        
        if (signImage) {
            comButton.hidden = YES;
        }else{
            comButton.hidden = NO;
            [comButton setTitle:@"重新签名" forState:UIControlStateNormal];
            [comButton setTitle:@"重新签名" forState:UIControlStateHighlighted];
            NSString* transTime = [self.screenData objectForKey:@"transTime"];
            if (![NSString isNilOrEmpty:transTime]) {
                if (![ZZTongUtility compareTime:transTime]) {
                    comButton.enabled = NO;
                }
            }
        }
    }

    if (signImage) {
        bgView.hidden = YES;
        UIImageView* imageView = [[UIImageView alloc]initWithImage:signImage];
        imageView.frame = CGRectMake(0, 0, bgScrollView.frame.size.width, signImage.size.height);
        [imageView setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
        [bgScrollView addSubview:imageView];
        [imageView release];
        
        CGSize size = bgScrollView.contentSize;
        size.height = signImage.size.height + 10;
        bgScrollView.contentSize = size;
        
//        [self addSuccessImage];
    }else{
        bgScrollView.contentSize = CGSizeMake(bgScrollView.frame.size.width, 1060);
        
        [comButton setBackgroundImage:[[UIImage imageNamed:@"bluebutton.png"] stretchableImageWithLeftCapWidth:9 topCapHeight:0] forState:UIControlStateNormal];
        
        [comButton setBackgroundImage:[[UIImage imageNamed:@"bluebuttonhover.png"] stretchableImageWithLeftCapWidth:9 topCapHeight:0] forState:UIControlStateHighlighted];
        
        CGRect signRect = signView.frame;
        
        UIButton* sButton = [UIButton buttonWithType:UIButtonTypeCustom];
        sButton.backgroundColor = [UIColor clearColor];
        [sButton setTitle:@"点击此处进行签名" forState:UIControlStateNormal];
        [sButton setTitleColor:kGrayFontColor forState:UIControlStateNormal];
        sButton.titleLabel.font = kSecondBigFont;
        [sButton addTarget:self action:@selector(addSign) forControlEvents:UIControlEventTouchUpInside];
        sButton.frame = CGRectMake( 5, 24, signRect.size.width - 10 , signRect.size.height - 29);
        self.signButton = sButton;
        [signView addSubview:self.signButton];
        
        if (bussinesType && [bussinesType isEqualToString:transRecord]) {
            [self addSuccessImage];
            self.signButton.hidden = YES;
        }
        
        aboveView.layer.cornerRadius = 5.0;
        aboveView.layer.borderColor = [UIColor redColor].CGColor;
        aboveView.layer.borderWidth = 1;
        
        signView.layer.cornerRadius = 5.0;
        signView.layer.borderColor = [UIColor redColor].CGColor;
        signView.layer.borderWidth = 1;
        
        [self setLabelData];

    }
    if (!comButton.hidden) {
        CGRect frame = bgScrollView.frame;
        frame.size.height -= 67;
        bgScrollView.frame = frame;
    }

    if (!iOS7Later) {
        CGRect frame = bgScrollView.frame;
        frame.size.height += frame.origin.y;
        frame.origin.y = 0;
        bgScrollView.frame = frame;
    }
}
- (void)updateUI:(UIImage*)sign_ withPhone:(NSString*)phone_{
    if(comButton.hidden){
        comButton.hidden = NO;
        CGRect frame = bgScrollView.frame;
        frame.size.height -= 37;
        bgScrollView.frame = frame;
    }
    NSString* bussinesType = [screenData objectForKey:kBusinissType];
    if (bussinesType && [bussinesType isEqualToString:transRecord]) {
        comButton.enabled = NO;
    }
    self.signButton.hidden = NO;
    self.signButton.enabled = NO;
    [self.signButton setTitle:@"" forState:UIControlStateDisabled];
    
    [self.signButton setBackgroundImage:sign_ forState:UIControlStateDisabled];
    
    //交易成功盖章
    [self addSuccessImage];
    //
    
}
- (void)signCallback:(UIImage*)image withPhone:(NSString*)phone_{
    NSString* transTime = [screenData objectForKey:@"transTime"];
    
    if (![ZZTongUtility compareTime:transTime]) {
        [HPUIENG showAlert:@"每日22时55分前可对当日交易进行重新签名上传，逾期不可"];
        return;
    }
    
    self.signImage = image;
    self.mobilePhone = phone_;
    LOG(@"signImage:%@  phone:%@",image,phone_);
    [ZZT_UIENG showNetWaiting];
    
    [self performSelectorOnMainThread:@selector(updateUI:withPhone:) withObject:image withObject:phone_ waitUntilDone:YES];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [self sendReq:image withPhone:phone_];
    });
    
}

//截取iphone屏幕全屏
-(UIImage*)screenshot
{
//	UIGraphicsBeginImageContextWithOptions(CGSizeMake(bgView.frame.size.width, bgView.frame.size.height),NO,[UIScreen mainScreen].scale);
    UIGraphicsBeginImageContext(CGSizeMake(bgView.frame.size.width, bgView.frame.size.height));
    [bgView.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
//    UIImageWriteToSavedPhotosAlbum(viewImage, nil, nil, nil);
    return viewImage;
}

- (void)sendReq:(UIImage*)image withPhone:(NSString*)phone{
    NSData* data = UIImageJPEGRepresentation(image, .5);
    NSString* hexString = [Utility toHexString:data];
    NSString* crc = [Utility crc32:data];
    
    UIImage* bgImage = [self screenshot];
    
//    bgImage = [bgImage getSubImage:CGRectMake(5, 20, bgImage.size.width - 10, bgImage.size.height - 80)];
    
    NSData* bgData = UIImageJPEGRepresentation(bgImage, .5);
    NSString* bgHexString = [Utility toHexString:bgData];
    NSString* bgCrc = [Utility crc32:bgData];
    
    
    NSString* transTime = [screenData objectForKey:@"transTime"];
    NSString* transSN = [screenData objectForKey:@"transSN"];
    
    ZZTongClientEngine* zztEngine = [ZZTongClientEngine sharedInstance];
    NSDictionary* params = nil;
    if (phone) {
        params = @{@"sign": hexString,
                   KEY_CHANNEL:[zztEngine getChannel],
                   @"signCheck" : crc,
                   @"bill" : bgHexString,
                   @"billCheck" : bgCrc,
                   @"transTime" : transTime,
                   @"transSN" : transSN,
                   KEY_ACCOUNT: DES_ENC(ZZT_CLIENG.accountInfo.account),
                   KEY_PHONE: DES_ENC(phone)};
    }else{
        params = @{@"sign": hexString,
                   KEY_CHANNEL:[zztEngine getChannel],
                   @"signCheck" : crc,
                   @"bill" : bgHexString,
                   @"billCheck" : bgCrc,
                   @"transTime" : transTime,
                   @"transSN" : transSN,
                   KEY_ACCOUNT: DES_ENC(ZZT_CLIENG.accountInfo.account)};
    }
    
    [zztEngine.netEngine sendRequest:NET_ACTION_UPLOAD_SIGN withParams:params withDelegate:self withAlertFlag:NO];
}
- (void)responseCallBackSuccess:(NSString *)action withData:(NSDictionary *)respData{
    if ([action isEqualToString:NET_ACTION_UPLOAD_SIGN]) {
        [HPUIENG removeWaiting];
    }
}
- (void)reSendReq{
    [ZZT_UIENG showNetWaiting];
     [self sendReq:self.signImage withPhone:self.mobilePhone];
}
- (void)doCancel{
    
}
- (void)responseCallBackFailed:(NSString *)action withErrCode:(NSString *)errCode withErrMsg:(NSString *)msg{
    if ([action isEqualToString:NET_ACTION_UPLOAD_SIGN]) {
        if (![errCode isEqualToString:@"8"]) {//＝8为网络不可用
            if ([errCode isEqualToString:@"S364"]) {
                [HPUIENG showAlert:msg];
            }else{
                AlertCommandData* commandOK = [[AlertCommandData alloc] initCommand:@"重新发送" function:@selector(reSendReq)];
                AlertCommandData* commandCancel = [[AlertCommandData alloc]initCommand:@"取消" function:@selector(doCancel)];
                AlertData* alertData = [[AlertData alloc] initAlertData:self title:@"提示" message:@"签购单发送失败!" commands:commandOK,commandCancel, nil];
                [HPUIENG showAlertWithData:alertData];
            
                [commandCancel release];
                [commandOK release];
                [alertData release];
            }
        }else{
            [HPUIENG showAlert:msg];
        }
    }
}
- (void)addSign{
    CallbackData* callback_ = [[CallbackData alloc]initWithTarget:self callback:@selector(signCallback:withPhone:)];
    LOG(@"signtrans addsign:%@",callback_.target);
    NSString* amount = [self.screenData objectForKey:KEY_AMOUNT];
    amount = [Utility getFormatMoneyAndSymbol:amount];
    
    [HPUIENG showScreen:SCR_ADD_USER_SIGN params:@{KEY_CALLBACK:callback_,
                                                   KEY_AMOUNT:amount}];
    [callback_ release];
}

- (void)setLabelData{
    if (self.screenData) {
        NSString* tempStr = DES_DEC([self.screenData objectForKey:@"shopName"]);
        if (tempStr) {
            merchantLabel.text = tempStr;
            
            [Utility adjustFontSizeWithLable:merchantLabel size:16];
            
        }
        
        tempStr = DES_DEC([self.screenData objectForKey:@"merchantcode"]);
        if (tempStr) {
            merchantNoLabel.text = tempStr;
        }
        
        tempStr = [self.screenData objectForKey:@"csn"];
        if (!tempStr)
        {
//            tempStr = SwiperService.csn; // mcm
            tempStr = [HPSwiperContext sharedInstance].connectedDeviceCSN; // mcm new
        }
        else
        {
            tempStr = DES_DEC(tempStr);
        }
        if (tempStr) {
            terminalNoLabel.text = tempStr;
            [Utility adjustFontSizeWithLable:terminalNoLabel size:16];
        }
        
//        tempStr = [self.screenData objectForKey:@""];
//        if (tempStr) {
//            operatiorNoLabel.text = tempStr;
//        }
        
        NSString* tranMediaType = [self.screenData objectForKey:@"tranMediaType"];
        
        tempStr = [Utility encryptCardID:[self.screenData objectForKey:@"cardNoOut"]];
        if (tempStr) {
            if (![NSString isNilOrEmpty:tranMediaType]) {
                cardNumberLabel.text = [[tempStr stringByAppendingString:@" /"] stringByAppendingString:tranMediaType];
            }else{
                cardNumberLabel.text = tempStr;
            }
        }

        
        tempStr = DES_DEC([self.screenData objectForKey:@"issuerId"]);
        if (tempStr) {
            issNOLabel.text = tempStr;
        }
        
        tempStr = DES_DEC([self.screenData objectForKey:@"specialNumber"]);
        if (tempStr) {
            acqNoLabel.text = tempStr;
        }
        
        if (tempStr) {
            txnTypeLabel.text = @"消费/SALE";
        }
//        tempStr = [self.screenData objectForKey:@""];
//        if (tempStr) {
//            expDateLabel.text = tempStr;
//        }
//        tempStr = [self.screenData objectForKey:@""];
//        if (tempStr) {
//            vaucherNoLabel.text = tempStr;
//        }
//        tempStr = [self.screenData objectForKey:@""];
//        if (tempStr) {
//            authNoLabel.text = tempStr;
//        }
        
        tempStr = [self.screenData objectForKey:@"transSN"];
        if (tempStr) {
            batchNoLabel.text = tempStr;
        }
        
        
        tempStr = [Utility getFormatDate:[self.screenData objectForKey:@"transTime"]];
        if (tempStr) {
            dateTimeLabel.text = tempStr;
        }
        
        tempStr = [self.screenData objectForKey:@""];
        if (tempStr) {
            refNoLabel.text = tempStr;
        }
        
        tempStr = [self.screenData objectForKey:@"cardOrganization"];
        if (tempStr) {
            cardORGLabel.text = tempStr;
        }
        
        tempStr = [Utility getFormatMoneyAndSymbol:[self.screenData objectForKey:KEY_AMOUNT]];
        if (tempStr) {
            amountLabel.text = tempStr;
        }
        if (tempStr) {
            tipsLabel.text = @"0";
        }
        tempStr = [self.screenData objectForKey:@""];
        if (tempStr) {
            remarksLabel.text = tempStr;
        }
    }
}
- (void)hideNaviBar{
    NSString* bussType = [self.screenData objectForKey:kBusinissType];
    if (bussType && [bussType isEqualToString:transRecord]) {
        [ZZT_UIENG hideNavigationBar:NO];
        
        CGRect frame = bgScrollView.frame;
        frame.size.height += frame.origin.y;
        frame.origin.y = 0;
        bgScrollView.frame = frame;
    }else{
        [ZZT_UIENG hideNavigationBar:YES];
    }
}
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [self hideNaviBar];
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear: animated];
    [self hideNaviBar];
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

- (void)dealloc {
    self.signButton = nil;
    [bgScrollView release];
    [aboveView release];
    [signView release];
    [merchantLabel release];
    [merchantNoLabel release];
    [terminalNoLabel release];
    [operatiorNoLabel release];
    [cardNumberLabel release];
    [issNOLabel release];
    [acqNoLabel release];
    [txnTypeLabel release];
    [expDateLabel release];
    [batchNoLabel release];
    [vaucherNoLabel release];
    [authNoLabel release];
    [dateTimeLabel release];
    [refNoLabel release];
    [cardORGLabel release];
    [amountLabel release];
    [tipsLabel release];
    [remarksLabel release];
    [comButton release];
    [bgView release];
    [super dealloc];
}
- (void)viewDidUnload {
    [bgScrollView release];
    bgScrollView = nil;
    [aboveView release];
    aboveView = nil;
    [signView release];
    signView = nil;
    [merchantLabel release];
    merchantLabel = nil;
    [merchantNoLabel release];
    merchantNoLabel = nil;
    [terminalNoLabel release];
    terminalNoLabel = nil;
    [operatiorNoLabel release];
    operatiorNoLabel = nil;
    [cardNumberLabel release];
    cardNumberLabel = nil;
    [issNOLabel release];
    issNOLabel = nil;
    [acqNoLabel release];
    acqNoLabel = nil;
    [txnTypeLabel release];
    txnTypeLabel = nil;
    [expDateLabel release];
    expDateLabel = nil;
    [batchNoLabel release];
    batchNoLabel = nil;
    [vaucherNoLabel release];
    vaucherNoLabel = nil;
    [authNoLabel release];
    authNoLabel = nil;
    [dateTimeLabel release];
    dateTimeLabel = nil;
    [refNoLabel release];
    refNoLabel = nil;
    [cardORGLabel release];
    cardORGLabel = nil;
    [amountLabel release];
    amountLabel = nil;
    [tipsLabel release];
    tipsLabel = nil;
    [remarksLabel release];
    remarksLabel = nil;
    [comButton release];
    comButton = nil;
    [bgView release];
    bgView = nil;
    [super viewDidUnload];
}
- (IBAction)comButtonClick:(id)sender {
    NSString* bussinesType = [screenData objectForKey:kBusinissType];
    //    UIImage* signImage = [self.screenData objectForKey:kSignImage];
    
    if (bussinesType && [bussinesType isEqualToString:transRecord]) {
        NSString* transTime = [self.screenData objectForKey:@"transTime"];
        if (![NSString isNilOrEmpty:transTime]) {
            if (![ZZTongUtility compareTime:transTime]) {
                [HPUIENG showAlert:@"每日22时55分前可对当日交易进行重新签名上传，逾期不可"];
                return;
            }
        }
        
        [self addSign];
    }else{
        [self goBack];
        self.canSave = NO;
    }
}

@end
